import QueryString from "qs";
import {QuerySourceType} from "../../server/types";
import {MasApiType} from "ls-base-lib/dist/src/library/AwaitTo/ToResult/types";
import ToResult from "ls-base-lib/dist/src/library/AwaitTo/ToResult";

/**
 * 处理queryJson，参将将被原地改变，用于小安易连查询（分页和普通）
 * @param query 带queryJson的类型
 */
export function dealQueryParam(query: QuerySourceType<any>) {
  if (query.queryJson) {
    for (const key in query.queryJson) {
      if (query.queryJson[key] === '' || query.queryJson[key] === null || query.queryJson[key] === undefined) {
        delete query.queryJson[key];
      }
    }
    if (Object.keys(query.queryJson).length > 0)
      query.queryJson = JSON.stringify(query.queryJson);
    else
      delete query.queryJson;
  }
}

/**
 * 处理小安易连保存体，用于代码生成器原封SaveForm
 * @param data 数据体
 * @param entityName 实体名称
 * @param type 默认为Form，如果带文件用FormData
 */
export function dealSaveData<T extends { ID?: string }>(data: T, entityName: string, type: 'Form' | 'FormData' = 'Form') {
  if (type === 'Form') {
    let postData: any = {
      [entityName]: data
    };
    if (data.ID)
      postData.keyValue = data.ID;
    return QueryString.stringify(postData);
  } else {
    const formData = new FormData();
    for (const key in data) {
      if (data[key] !== null)
        formData.append(`${entityName}[${key}]`, data[key] as any);
    }
    formData.append('businessID', 'AllFile');
    if (data.ID)
      formData.append('keyValue', data.ID);
    return formData;
  }
}

/**
 * 处理保存类接口由于后端未返回data导致的错误判定
 * @param result
 */
export function getBooleanResult(result: ToResult<MasApiType>) {
  result.getInfo();
  return result.data?.data.code === 200;
}
